package cn.com.wxd.common.framedata;

import java.sql.Connection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.common.DateUtil;
import cn.com.wxd.common.framedata.dao.Persistence;
import cn.com.wxd.common.framedata.entity.FrameDataInfo;
import cn.com.wxd.common.util.JdbcUtil;

/**
 * 框架数据工具类
 *
 * @author wangxudong
 */
public class FrameDataUtil {

    private static final Logger log = LoggerFactory.getLogger(FrameDataUtil.class);

    /**
     * 根据名称获取相应的数据
     *
     * @param name
     *
     * @return
     *
     * @throws Exception
     */
    public static String getDataByName(String name) throws Exception {
        Connection connection = JdbcUtil.getConnection();
        Persistence persistence = new Persistence(connection);
        FrameDataInfo frameDataInfo = persistence.selectRecordByName(name);
        JdbcUtil.closeConn(connection);
        if (frameDataInfo != null) {
            return frameDataInfo.getData();
        }
        log.warn("查询到的数据为NULL" + name);
        return null;
    }

    /**
     * 保存数据，根据name保存Data数据，如果存在该数据，则替换到之前到数据
     * 该方法我们只关心保存现有的数据，不用关心具体如何实现和具体是更新还是保存
     *
     * @param name
     * @param data
     *
     * @return
     *
     * @throws Exception
     */
    public static boolean saveFrameData(String name, String data) throws Exception {
        FrameDataInfo fdi = new FrameDataInfo();
        if (name == null) {
            throw new Exception("存入frame_data表中的数据name不能为空");
        }
        fdi.setName(name);
        fdi.setUpdateTime(DateUtil.getDatetimeStr());
        fdi.setData(data);
        Connection connection = JdbcUtil.getConnection();
        Persistence persistence = new Persistence(connection);
        try {
            FrameDataInfo frameDataInfo = persistence.selectRecordByName(name);
            if (frameDataInfo == null) {
                return persistence.addRecord(fdi);
            } else {
                return persistence.updateRecord(fdi);
            }
        } catch (Exception e) {
            log.error(e.getMessage() + e);
        } finally {
            JdbcUtil.closeConn(connection);
        }
        return false;
    }
}
